#!/bin/bash

# 快速构建和启动脚本
IMAGE_NAME="rocketmq-rate-limit-demo:1.0.0"
CONTAINER_NAME="rocketmq-rate-limit-app"

echo "快速构建和启动RocketMQ应用..."

# 检查RocketMQ网络是否存在
if ! docker network ls | grep -q "rocketmq"; then
    echo "RocketMQ网络不存在，正在创建..."
    docker network create rocketmq
    if [ $? -eq 0 ]; then
        echo "✓ RocketMQ网络创建成功"
    else
        echo "错误: 无法创建RocketMQ网络"
        exit 1
    fi
    echo ""
else
    echo "✓ RocketMQ网络已存在"
    echo ""
fi

# 构建镜像
echo "构建镜像..."
docker build -t $IMAGE_NAME .

# 停止并删除旧容器
docker stop $CONTAINER_NAME 2>/dev/null || true
docker rm $CONTAINER_NAME 2>/dev/null || true

# 启动新容器
echo "启动容器..."
docker run -d \
    --name $CONTAINER_NAME \
    --network rocketmq \
    -p 8080:8080 \
    --restart unless-stopped \
    -e SPRING_PROFILES_ACTIVE=prod \
    -e ROCKETMQ_NAMESRV_ADDR=rmqnamesrv:9876 \
    -e JAVA_OPTS="-server -Xms512m -Xmx1g -Xmn256m -XX:+UseG1GC -XX:+UseContainerSupport" \
    $IMAGE_NAME

echo "应用已启动，访问地址: http://localhost:8080"
echo "查看日志: docker logs -f $CONTAINER_NAME"
echo "RocketMQ NameServer: rmqnamesrv:9876 (容器网络)"
